package org.example.state;

import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.example.flink.pojo.WaterSensor;
import org.example.function.WaterSensorFunction;

import java.time.Duration;

/**
 * @Author: tang
 * @Description:
 * @Date 2025/2/24 16:51
 */
public class KeyedTtlStateDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();

        environment.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> streamOperator = environment
                .socketTextStream("127.0.0.1", 7777)
                .map(new WaterSensorFunction())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                                .withTimestampAssigner((TimestampAssignerSupplier<WaterSensor>)
                                        context -> (element, recordTimestamp) -> element.getVc() * 1000L)
                );

        streamOperator
                .keyBy(WaterSensor::getId)
                .process(
                        new KeyedProcessFunction<String, WaterSensor, String>() {

                            // 定义状态
                            private ValueState<Integer> valueState;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                super.open(parameters);
                                StateTtlConfig stateTtlConfig = StateTtlConfig.newBuilder(Time.seconds(10))
                                        .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                        .build();
                                // 初始化 valueState，只能在这个地方初始化
                                ValueStateDescriptor<Integer> valueStateDescriptor = new ValueStateDescriptor<>("valueState", Types.INT);
                                // 设置 TTL
                                valueStateDescriptor.enableTimeToLive(stateTtlConfig);
                                valueState = getRuntimeContext().getState(valueStateDescriptor);
                            }

                            @Override
                            public void processElement(WaterSensor value,
                                                       KeyedProcessFunction<String, WaterSensor, String>.Context ctx,
                                                       Collector<String> out) throws Exception {
                                Integer valueVc = value.getVc();
                                if (valueVc > 5 && valueVc < 10) {
                                    valueState.update(valueVc);
                                }
                                out.collect(valueState.value() + "");
                            }
                        }
                ).print();

        environment.execute();


    }

}
